/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.activities;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.geoscheduler.android.GSContext;
import org.geoscheduler.android.R;
import org.geoscheduler.android.exceptions.GSContextNotInitializedException;
import org.geoscheduler.android.tools.DBHelper;
import org.geoscheduler.android.tools.GSMenuBuilder;
import org.geoscheduler.android.tools.LogCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Setup Activity of GeoScheduler client application
 * 
 * @author paja 
 * @author srakyi
 */
public class Setup extends Activity {
	
	public static final String LOGTAG = Setup.class.getName();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		setContentView(R.layout.setup);

		final Context ctx = this;
		
		/* Initialize GSContext */
		// FIXME [srakyi] we shouldn't (and don't need to) do this in EVERY activity
		GSContext.loadPrefs(ctx);

		/* Create DB button listener */
		Button btnDBCreate = (Button) findViewById(R.id.setup_db_create);
		btnDBCreate.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				try {
					DBHelper.deleteDB(ctx);
					DBHelper.createDB(ctx, new LogCallback() { 
						@Override						
						public void writeLog(String msg) {
							log(msg);
						}});
					log(getString(R.string.setup_db_created));
				} catch (Exception e) {
					log(getString(R.string.setup_db_create_error));

					/* Print StackTrace to log */ 
					StringWriter sw = new StringWriter();			
					e.printStackTrace(new PrintWriter(sw));
					String err = sw.toString();
					log(err);
				}
			}
		});

		/* Create DB button listener */
		Button btnDBRemove = (Button) findViewById(R.id.setup_db_remove);
		btnDBRemove.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				try {
					DBHelper.deleteDB(ctx);
					log(getString(R.string.setup_db_removed));
				} catch (Exception e) {
					log(getString(R.string.setup_db_remove_error));

					/* Print StackTrace to log */ 
					StringWriter sw = new StringWriter();			
					e.printStackTrace(new PrintWriter(sw));
					String err = sw.toString();
					log(err);
				}
			}
		});
		
		/* Initialize URL input field (with previous value) */
		EditText etSrvURL = (EditText) findViewById(R.id.setup_server_in_url);
		try {
			String oldUrl = (String)GSContext.getPref(GSContext.PREFS_SERVER_URL);
			if ((oldUrl != null) && (!"".equals(oldUrl.trim()))) {
				etSrvURL.setText(oldUrl);
			} else {
				etSrvURL.setText(getText(R.string.default_server_url));
			}
		} catch (GSContextNotInitializedException e) {
			Log.e(LOGTAG, "Unexpected exception during activity initialization.", e);
		}
		
		/* Initialize server URL save button */
		Button btnSrvSave = (Button) findViewById(R.id.setup_server_save);
		btnSrvSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				EditText etSrvURL = (EditText) findViewById(R.id.setup_server_in_url);
				String srvUrl = etSrvURL.getText().toString();
				if (!srvUrl.endsWith("/")) {
					srvUrl = srvUrl + "/";
				}
				
				try {
					GSContext.getServerAPIVersionProvider().getVersion(srvUrl);
					
					GSContext.putPref(GSContext.PREFS_SERVER_URL, srvUrl, ctx);
					etSrvURL.setText(srvUrl);

//					showAlert(getString(R.string.label_info), 0, getString(R.string.setup_msg_url_saved), getString(R.string.label_ok), true);
					(new AlertDialog.Builder(Setup.this)).
						setIcon(R.drawable.button_ok).
						setTitle(R.string.label_info).
						setMessage(R.string.setup_msg_url_saved).
						setPositiveButton(R.string.label_ok, null).
						create().
						show();
				} catch (Exception e) {
//					showAlert(getString(R.string.label_error), 0, getString(R.string.setup_err_url_check_failed), getString(R.string.label_ok), true);
					(new AlertDialog.Builder(Setup.this)).
						setIcon(R.drawable.stop).
						setTitle(R.string.label_error).
						setMessage(R.string.setup_err_url_check_failed).
						setPositiveButton(R.string.label_error, null).
						create().
						show();
					Log.e(LOGTAG, "Obtaining server API version failed.", e);
				}
			}
		});
	}
	
	/**
	 * Write message into log view on setup screen
	 * @param msg Given message
	 */
	public void log(String msg) {		
		EditText logTextView = (EditText) findViewById(R.id.setup_log);
		
		logTextView.getText().append(msg + "\n");

		/* Hack to get a Vertical scrollbar range */
		int scrollRange = new TextView(this) {
			int myComputeVerticalScrollRange() {
				return computeVerticalScrollRange();
			}
		}.myComputeVerticalScrollRange();
		
		logTextView.scrollTo(0, scrollRange);
	}

	/**
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		return GSMenuBuilder.createOptionsMenu(menu, this, 
								GSMenuBuilder.Item.LOGIN,
								GSMenuBuilder.Item.LIST);
	}
	
	/**
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.Menu.Item)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		
		return GSMenuBuilder.menuItemSelected(this, item);
	}
}
